package com.ren.fm.constant;

import com.alibaba.fastjson.JSON;
import com.ren.cache.entity.CacheItemVo;
import com.ren.cache.handler.CacheHandler;
import com.ren.fm.entity.ReclFm;
import com.ren.utils.canal.CanalBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @ClassName: CachePrefix
 * @Description: TODO
 * @Author: RZY
 * @DATE: 2022/7/13 12:35
 * @Version: v1.0
 */

@Component
@Slf4j
public class CachePrefix {

    @Autowired
    CacheHandler cacheHandler;

    //热点FM缓存前缀
    public final static String FM_ITEM_KEY_PREFIX = "fm_item_key";

    //前台FM缓存分页前缀
    public final static String FM_PAGE_KEY_PREFIX = "fm_page_key";

    //过期时间
    public final static long timeOut = 30L;

    //tableName和prefix的映射关系
    public final static Set<String> tableSet = new HashSet<>();

    public final static ThreadLocalRandom random = ThreadLocalRandom.current();

    static {
        tableSet.add("recl_fm");
    }

    public void updateCache(String tableName, CanalBean canalBean) {
        //获取CanalBean需要序列化的JSON数据
        String data = canalBean.getData();
        if(tableName.equals("recl_fm")) {
            List<ReclFm> reclFms = JSON.parseArray(data, ReclFm.class);
            reclFms.forEach(value -> {
                String key = String.format("%s::%s::%s", "recl_fm", FM_ITEM_KEY_PREFIX, value.getId());
                try {
                    //因为MybatisPlus采用了逻辑删除，所以需要判断isDeleted属性
                    if(value.getIsDeleted())
                        //删除缓存
                        cacheHandler.delCache(key);
                    //更新缓存
                    else
                        cacheHandler.putCache(key, value, timeOut + random.nextLong(5, 8));
                } catch (Exception e) {
                    log.info("缓存更新失败: {}", value);
                }
            });
        }
    }

    public void deleteCache(String tableName, CanalBean canalBean) {
        //获取CanalBean需要序列化的JSON数据
        String data = canalBean.getData();
        if(tableName.equals("recl_fm")) {
            List<ReclFm> reclFms = JSON.parseArray(data, ReclFm.class);
            log.info(String.valueOf(reclFms));
            reclFms.forEach(value -> {
                String key = String.format("%s::%s::%s", "recl_fm", FM_ITEM_KEY_PREFIX, value.getId());
                try {
                    //删除缓存
                    cacheHandler.delCache(key);
                } catch (Exception e) {
                    log.info("缓存更新失败: {}", value);
                }
            });
        }
    }

    public static boolean isContainsTableName(String tableName) {
        return tableSet.contains(tableName);
    }

}
